package com.arm.controller.api.admin.login;

import com.arm.controller.BaseController;
import com.arm.def.Constant;
import com.arm.def.MessageConstant;
import com.arm.module.AdminUser;
import com.arm.module.dto.UserLogin;
import com.arm.service.AdminUserService;
import com.arm.service.MenuService;
import com.arm.service.RoleService;
import com.arm.tools.ValidateCode;
import com.arm.tools.myRunTime.MyRunTimeExcption;
import com.arm.tools.result.ResultObj;
import com.arm.tools.result.ReturnCode;
import io.swagger.annotations.*;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;

/**
 * Created by Andrew  on 2017/2/26.
 */
@Api(description = "后台登录接口")
@RestController
@RequestMapping(value = "/api/admin/login")
public class AdminLoginController extends BaseController {
    /*@Autowired
    RedisCache redisCache;*/
    @Autowired
    RoleService roleService;
    @Autowired
    MenuService menuService;
    @Autowired
    AdminUserService adminUserService;


    /**
     * 获取验证码
     */
    @ApiOperation(value = "获取验证码", notes = "获取验证码")
    @GetMapping(value = "/getVerificatioCode")
    public void getVerificationCode(HttpServletRequest request, HttpServletResponse response) {

        System.out.println("==========================================================================================================");
        response.setContentType("image/jpeg");// 设置相应类型,告诉浏览器输出的内容为图片
        response.setHeader("Pragma", "No-cache");// 设置响应头信息，告诉浏览器不要缓存此内容
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expire", 0);
        ValidateCode vCode = new ValidateCode(160, 40, 5, 150);
        try {
            String key = Constant.SESSION_KEY_RANDOM_VALIDATE_CODE;
            super.session.setAttribute(key, vCode.getCode());
            logger.info("随机验证码：" + vCode.getCode());
            vCode.write(response.getOutputStream());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    @ApiOperation(value = "后台登录", notes = "后台登录")

    @PostMapping("login")
    public ResultObj<AdminUser> Login(@RequestBody UserLogin userLogin) {
        //applicationContext.

        String code = userLogin.getCode();
        ResultObj resultObj = new ResultObj();
        try {

            // Map<String, String> map = this.showRequestParameters(request);
            String randomCode = (String) super.httpServletRequest.getSession().getAttribute(Constant.SESSION_KEY_RANDOM_VALIDATE_CODE);

            if (StringUtils.isBlank(code)) {
                throw new MyRunTimeExcption("code is null");
            }
            if (StringUtils.isBlank(randomCode)) {
                throw new MyRunTimeExcption("randomCode is null");
            }
            if (!code.toLowerCase().equals(randomCode.toLowerCase())) {
                logger.info(code + "<<<randomCode>>>" + randomCode);
                throw new MyRunTimeExcption(MessageConstant.CODE_ERRO);
            }
            AdminUser adminUser = adminUserService.login(new HashMap<String, String>() {{
                put("userName", userLogin.getUserName());
                put("passWord", userLogin.getPassWord());
            }});
            if (adminUser == null) {
                throw new MyRunTimeExcption(MessageConstant.USERNAME_PASSWORD_ERRO);
            }
            super.httpServletRequest.getSession().setAttribute(Constant.SESSION_KEY_ADMIN_USER_LOGIN, adminUser);
            resultObj.setData(adminUser);
            resultObj.setMsg(MessageConstant.LOGIN);

        } catch (MyRunTimeExcption myRunTimeExcption) {
            myRunTimeExcption.printStackTrace();
            resultObj.setCode(ReturnCode.FAIL.getCode());
            resultObj.setMsg(myRunTimeExcption.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            resultObj.setCode(ReturnCode.FAIL.getCode());
            resultObj.setMsg(e.getMessage());
        }

        return resultObj;

    }

    @ApiOperation(value = "后台登出", notes = "后台登出")
    @RequestMapping(value = "/loginOut", method = RequestMethod.POST)
    @ResponseBody
    public String loginOut(HttpServletRequest request) {
        System.out.println("===============================loginOut============================================>>>>>>");

        ResultObj resultObj = new ResultObj();
        try {
            request.getSession().invalidate();
        } catch (MyRunTimeExcption myRunTimeExcption) {
            myRunTimeExcption.printStackTrace();
            resultObj.setCode(ReturnCode.FAIL.getCode());
            resultObj.setMsg(myRunTimeExcption.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            resultObj.setCode(ReturnCode.FAIL.getCode());
            resultObj.setMsg(e.getMessage());
        }
        return resultObj.toJson();
    }
}
